<template>
  <t-skeleton :loading="loading" animation="gradient">
    <t-form :data="formData" label-width="auto" reset-type="initial" style="width: 400px" @submit="handleSave">
      <t-form-item
        v-for="_ in configList"
        :key="_.value"
        :label="_.label"
        :name="_.value.toString()"
        :rules="[{ required: true, message: '请输入天数' }]"
      >
        <t-input-number
          v-model:value="formData[_.value]"
          :decimal-places="0"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item>
        <t-button theme="default" type="reset">重置</t-button>
        <t-button theme="primary" type="submit" :loading="loadingSubmit">保存</t-button>
      </t-form-item>
    </t-form>
  </t-skeleton>
</template>

<script setup lang="ts">
import { MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';

import { noticeConfigCRUD } from '@/api/config/common-config';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 配置列表
const configList = dictionaryStore.get('report_early_warning_config');
// 配置key
const configKey = 'report';
// 加载状态
const loading = ref(false);
// 表单数据
const formData = ref<Record<string, any>>({});
// 处理获取数据
const handleGetData = () => {
  loading.value = true;
  const params = {
    type: configKey,
  };
  noticeConfigCRUD
    .get(params)
    .then((data) => {
      formData.value = data.items || {};
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
onMounted(() => {
  handleGetData();
});
// 加载提交状态
const loadingSubmit = ref(false);
// 处理保存
const handleSave = ({ validateResult }: SubmitContext) => {
  if (validateResult !== true) return;
  loadingSubmit.value = true;
  const params = {
    type: configKey,
    items: formData.value,
  };
  noticeConfigCRUD
    .create(params)
    .then(() => {
      MessagePlugin.success('保存成功');
      handleGetData();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loadingSubmit.value = false;
    });
};
</script>
